import { LoginRequest, sysProfileRequest } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'
import router from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  getters: {},
  mutations: {
    setTokenMutation(state, payload) {
      state.token = payload
      setToken(payload)
    },
    setUserInfoMutation(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    async ActionsLogin(context, payload) {
      try {
        const res = await LoginRequest(payload)
        context.commit('setTokenMutation', res.data)
        console.log('5.登录成功', res)
        router.push('/')
      } catch (error) {
        console.log(error)
      }
    },
    // 使用.then的语法
    // ActionsLogin(context, payload) {
    //   LoginRequest(payload).then(res => {
    //     context.commit('setTokenMutations', res.data)
    //     console.log('5.登录成功', res)
    //     router.push('/')
    //   }).catch(error => {
    //     console.log(error)
    //   })
    // }

    async getUserInfoAction({ commit }, payload) {
      try {
        const res = await sysProfileRequest(payload)
        console.log(res)
        commit('setUserInfoMutation', res.data)
      } catch (err) {
        console.log('获取用户个人信息失败')
      }
    },

    logoutAction({ commit }) {
      commit('setTokenMutation', '')
      commit('setUserInfoMutation', {})
    }
  },
  module: {}
}
